import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_bsbdj/utils/toast.dart';

// ignore: must_be_immutable
class DownLoadPrompt extends Dialog {
  String downloadUrl;

  DownLoadPrompt(this.downloadUrl);

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: Container(
          width: 200,
          height: 150,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(5))),
          child: Column(
            children: <Widget>[
              Expanded(
                child: GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    color: Colors.white,
                    child: Text(
                      "下载",
                      style: TextStyle(decoration: TextDecoration.none),
                    ),
                  ),
                  onTap: () {
                    _downLoadTask(context);
                    Navigator.pop(context);
                  },
                ),
              ),
              Container(
                height: 1,
                color: Colors.grey,
              ),
              Expanded(
                child: GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    color: Colors.white,
                    child: Text(
                      "取消",
                      style: TextStyle(decoration: TextDecoration.none),
                    ),
                  ),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _downLoadTask(BuildContext context) async {
    await getExternalStorageDirectory().then((dir) async {
      String path = dir.path + "/flutter";
      if (await Directory(path).exists()) {
        print("====");
        var t = downloadUrl.split("/");
        File file = File("$path/${t[t.length - 1]}");
        if (await file.exists()) {
          Toast.toast(context, "文件已存在");
        } else {
          _downLoad(path);
        }
      } else {
        Directory(path).create(recursive: false).then((dirs) {
          print("++++");
          _downLoad(path);
        });
      }
    });
  }

  void _downLoad(String path) async {
    await FlutterDownloader.enqueue(
            url: downloadUrl,
            savedDir: path,
            showNotification: true,
            openFileFromNotification: true)
        .then((taskId) {
      print("down_load taskId=$taskId");
    }).catchError((e) {
      print(e);
    });
  }
}
